﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace StoryMaker.Common
{
    public class GenericCommand : ICommand
    {
        private Action _action;
        private Predicate<object> _canExecuteGetter;

        public GenericCommand()
        {

        }
        public GenericCommand(Action action)
            : this(action, null)
        {
        }

        public GenericCommand(Action action, Predicate<object> canExecuteGetter)
        {
            this._action = action;
            this._canExecuteGetter = canExecuteGetter;
        }

        public virtual bool CanExecute(object parameter)
        {
            if (_canExecuteGetter == null)
            {
                return true;
            }
            else
            {
                return _canExecuteGetter(parameter);
            }
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public virtual void Execute(object parameter)
        {
            if (_action != null)
            {
                _action();
            }
        }


    }
    /// <summary>
    /// This class allows a viewmodel to expose methods to UI elements
    /// without creating a separate class for each one.
    /// </summary>
    public class GenericCommand<T> : GenericCommand
    {
        private Action<T> _action;
        private Predicate<T> _canExecuteGetter;

        public GenericCommand(Action<T> action)
            : this(action, null)
        {
        }

        public GenericCommand(Action<T> action, Predicate<T> canExecute)
        {
            _action = action;
            this._canExecuteGetter = canExecute;
        }

        public override void Execute(object parameter)
        {
            if (_action != null)
            {
                _action((T)parameter);
            }
        }

        public override bool CanExecute(object parameter)
        {
            if (_canExecuteGetter == null)
            {
                return true;
            }
            else
            {
                return parameter is T && this._canExecuteGetter((T)parameter);
            }
        }
    }
}
